package com.study.reconnect;

import com.study.handler.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @ClassName: NettyServer
 * @Description:
 * @Date 2024/04/28 11:32
 * @Author songshaoqiu
 **/
public class NettyServer {
    public static void main(String[] args) {
        //创建只处理连接请求的线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(10);
        //创建只处理客户端读写业务的线程组
        NioEventLoopGroup workGroup = new NioEventLoopGroup(10);


        try {
            //创建服务端启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //配置参数
            serverBootstrap.group(bossGroup,workGroup)
                    //使用NioServerSocketChannel作为服务器的通道实现
                    .channel(NioServerSocketChannel.class)
                    //配置用于存放因没有空闲线程导致连接请求被咱存放到队列中的队列长度
                    .option(ChannelOption.SO_BACKLOG,1024)
                    //创建通道初始化的对象并配置该对象，向该对象中添加处理起来实现具体的业务处理
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //添加解码 处理器
                            // socketChannel.pipeline().addLast(new StringDecoder());
                            // //添加编码处理器
                            // socketChannel.pipeline().addLast(new StringEncoder());

                            //添加处理器，处理器里面是真正处理业务的
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("netty 服务端启动了");
            ChannelFuture bind = serverBootstrap.bind(9090);
            //同步阻塞的启动服务端
            bind.sync();
            //只要服务没关闭。该方法会一直阻塞
            System.out.println("netty 服务关闭--------->  执行 bind.channel().closeFuture().sync();");
            bind.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //断开所有连接并清理内存
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
